<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper" style="overflow:auto;background: #E5EBF1;margin: 10px;">
            <a-row style="display: flex;align-items: center;padding: 10px;border-bottom:1px solid #ccc;background: #FFFFFF;">
                <a-statistic :value-style="{ color: '#1890ff' }" style="flex:0 0 150px;text-align:center" title="总佣金" :precision="2" :value="userInfo.totalCommission?userInfo.totalCommission:0" />
                <a-statistic :value-style="{ color: '#faad14' }" style="flex:0 0 150px;text-align:center" title="已提现佣金" :precision="2" :value="userInfo.withdrawalCommission?userInfo.withdrawalCommission:0" />
                <a-statistic :value-style="{ color: '#52c41a' }" style="flex:0 0 150px;text-align:center" title="可提现佣金" :precision="2" :value="userInfo.surplusCommission?userInfo.surplusCommission:0" />
                <img :src="rmbIcon" />
                <span style="display: inline-block;" class="ml-2">最高获{{maxReward}}%现金奖励<span style="display: block;color:#b3abab;">推广四班云获取现金奖励 <a href="javascript:void()" class="ml-5" @click="showCalculatorModal">收益计算器</a></span></span>
            </a-row>
            <div style="display:flex;flex-wrap:wrap;">
                <a-card size="small" :title="false" v-for="(item,index) in data" style="width:19%;min-width:290px;margin:10px 0% 10px 1%;height:300px">
                    <div class="money-set-wrapper clearfix">
                        <div class="goods-img">
                            <img :src="item.goodsLogoUrl" alt="商品图片">
                        </div>
                        <div class="goods-explain">
                            <div class="margin-bottom-10"> {{item.goodsName}}</div>
                            <div style="font-size:20px">

                                <a-statistic :precision="2" :value="item.price">
                                    <template slot="prefix">
                                        ￥
                                    </template>
                                </a-statistic>
                            </div>
                        </div>
                    </div>
                    <div class="margin-bottom-10">佣金设置</div>
                    <div class="margin-bottom-6"><span v-if="item.firstReward!=0">自销提出比例:{{item.firstReward}}%</span><div v-else>&nbsp;</div></div>
                    <div class="margin-bottom-6"><span v-if="item.secondReward!=0">一级佣金比例:{{item.secondReward}}%</span><div v-else>&nbsp;</div></div>
                    <div class="margin-bottom-6"><span v-if="item.thirdReward !=0">二级佣金比例:{{item.thirdReward}}%</span><div v-else>&nbsp;</div></div>
                    <div class="margin-bottom-6"><span v-if="item.fourthReward!=0">三级佣金比例:{{item.fourthReward}}%</span><div v-else>&nbsp;</div></div>

                    <!-- <a-form :label-col="{ offset:1, span: 3}" :wrapper-col="{ span: 20 }" class="user-class">
                        <a-form-item label="" :label-col="{ offset:2, span: 3 }" class="reward">
                            <span class="reward-label">佣金规则:</span>
                            (推荐给客户首次购买能拿到的提成比例。)<a style="color:red;display:none;" @click="showModal">推广协议</a>
                        </a-form-item>
                        <a-form-item label="" :label-col="{ offset:2, span: 3 }" class="reward" v-if="item.firstReward">
                            <span class="reward-label">自销提出比例:</span>
                            <span style="width:60px;margin:0 0 0 10px;">{{item.firstReward}}%</span>
                            (推荐给客户首次购买能拿到的提成比例。)<a style="color:red;display:none;" @click="showModal">推广协议</a>
                        </a-form-item>
                        <a-form-item label="" :label-col="{ offset:2, span: 3}" class="reward" v-if="item.firstReward && item.secondReward">
                            <span class="reward-label">直属上级佣金比例:</span>
                            <span style="width:60px;margin:0 0 0 10px;">{{item.secondReward}}%</span>
                            (好友推荐给客户首次购买后，好友的上级能拿到的提成比例。)
                        </a-form-item>
                        <a-form-item label="" :label-col="{ offset:2, span: 3}" class="reward" v-if="item.firstReward && item.secondReward && item.thirdReward">
                            <span class="reward-label">间接上级佣金比例:</span>
                            <span style="width:60px;margin:0 0 0 10px;">{{item.thirdReward}}%</span>
                            (好友推荐给客户首次购买后，好友的上级的上级能拿到的提成比例。)
                        </a-form-item>
                        <a-form-item label="" :label-col="{ offset:2, span: 3}" class="reward" v-if="item.firstReward && item.secondReward && item.thirdReward && item.fourthReward">
                            <span class="reward-label">三级上级佣金比例:</span>
                            <span style="width:60px;margin:0 0 0 10px;">{{item.fourthReward}}%</span>
                            (好友推荐给客户首次购买后，好友的上级的上级的上级能拿到的提成比例。)
                        </a-form-item>
                    </a-form> -->
                    <div style="width:100%;text-align:center;margin-top:20px;">
                        <a-button style="margin:0 auto;width:80%" type="primary" @click="showShare">
                            <a-icon type="share-alt" />分享
                        </a-button>
                    </div>
                </a-card>
            </div>
        </div>
        <a-modal title="推广协议" :visible="ModalVisible" @cancel="hideModal" width="1000px">
            <template slot="footer">
                <a-button type="danger" @click="hideModal">关闭</a-button>
            </template>
            <div v-html="agreementMap.get('share')"></div>
        </a-modal>
        <a-modal title="收益计算器" :visible="CalculatorVisible" @cancel="hideCalculatorModal" width="1000px">
            <share-calculator v-if="CalculatorVisible"></share-calculator>
            <template slot="footer">
                <a-button type="danger" @click="hideCalculatorModal">关闭</a-button>
            </template>
        </a-modal>

        <a-modal :destroyOnClose="true" title="推广分享" :width="800" :visible="shareVisible" @cancel="()=>{shareVisible = false}">
            <a-form :label-col="{ offset:1, span: 4}" :wrapper-col="{ span: 19 }">
                <a-form-item label="分 享 网 址">
                    <a-input-search v-model="registerUrl" read-only @search="onCopy">
                        <a-button slot="enterButton">复制</a-button>
                    </a-input-search>
                    <br />
                    <a target="_blank" class="qcShareQQDiv" style="dispaly:block;" :href="shareRegisterUrl">分享到QQ</a>
                    <!-- <a style="margin-left: 20px" class="qcShareQQDiv" href="javascript:;" @click="WxShareInfo">分享到微信</a> -->
                </a-form-item>
                <a-form-item label="分享二维码">
                    <div class="qrcode" id="qrcode" ref="qrCodeUrl"></div>
                    <a @click="downloadQrCode" href="javascript:;" title="下载二维码" class="mr-1">点击下载</a>
                </a-form-item>
                <a-form-item label="分享方法">
                    <div style="padding:0 10px;" v-html="method"></div>
                </a-form-item>
            </a-form>
            <template slot="footer">
                <div>
                    <a-button type="primary" @click="()=>{shareVisible = false}">确认</a-button>
                </div>
            </template>
        </a-modal>
    </div>
</template>

<script>

import rmbIcon from "@/assets/rmb.png";
import { shareInfo, shareUserList, shareCrmList, getSignature } from "@/api/personal/userInfo";
import { components } from "@/utils/antTableComponents";
import QRCode from "qrcodejs2";
import { userPageListToTree } from "@/utils/tree";
import VueClipboard from "vue-clipboard2";
import wx from "weixin-js-sdk";
import Vue from "vue";
import { pageList } from "@/api/member/goods";
import { configList } from "@/api/member/config";
import { getCommissionConfig } from "@/api/system/config";
import { getAgreement } from "@/api/agreement";
import { getUserInfo } from "@/api/personal/userInfo";


Vue.use(VueClipboard);

import shareCalculator from "./shareCalculator.vue";

export default {
    components: {
        shareCalculator
    },
    data () {
        const columns = [
            {
                title: "姓名",
                dataIndex: "realName",
                key: "realName",
                align: "left",
                width: 120
            },
            {
                title: "手机号",
                dataIndex: "mobile",
                key: "mobile",
                width: 120
            },
            {
                title: "邮箱",
                dataIndex: "email",
                key: "email",
                width: 120
            },
            {
                title: "最后登录时间",
                dataIndex: "lastLoginDate",
                key: "lastLoginDate",
                width: 120
            },
            {
                title: "注册时间",
                dataIndex: "createDate",
                key: "createDate",
                width: 120
            }
        ];

        const crmColumns = [
            {
                title: "客户名称",
                dataIndex: "companyName",
                key: "companyName",
                width: 120
            },
            {
                title: "推荐人",
                dataIndex: "shareUserName",
                key: "shareUserName",
                width: 120
            },
            {
                title: "推荐等级",
                dataIndex: "grade",
                key: "grade",
                width: 120
            },
            {
                title: "首次交易时间",
                dataIndex: "payDate",
                key: "payDate",
                width: 120
            },
            {
                title: "首次交易金额",
                dataIndex: "salePrice",
                key: "salePrice",
                width: 120,
                customRender: (text, row, index) => {
                    if (text) {
                        return text + "元";
                    }
                }
            },
            {
                title: "最后登录时间",
                dataIndex: "loginDate",
                key: "loginDate",
                width: 120
            },
            {
                title: "注册时间",
                dataIndex: "registDate",
                key: "registDate",
                width: 120
            }
        ];
        //表格 头部 可伸缩
        this.components = components(columns);
        this.components2 = components(crmColumns);

        return {
            rmbIcon,
            loading: false,
            haveExpandSet: new Set(),
            dataKeySet: new Set(),
            registerUrl: "", //注册地址
            shareRegisterUrl: "", //分享注册地址
            form: this.$form.createForm(this, { name: "coordinated" }),
            header: { "Access-Token": Vue.ls.get("Access-Token") },
            tabKey: "1",
            columns, //我的团队
            crmColumns, //我的客户
            data: [],
            crmData: [],
            selectIds: [],
            selectedKeys: [],
            postData: {
                current: 1,
                size: 20,
                isReward: 1,//是否开启推广奖励
                companyName: "",
                realName: ""
            },
            pagination: {
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            paginationCrm: {
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.paginationCrm.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            method: "",
            rule: "",
            shareTitle: "", //分享的标题
            shareRemark: "", //分享描述
            goodsInfo: {},
            discountRate: 0,
            config: [],
            commissionConfig: [],
            maxReward: 0,
            agreementMap: new Map(),
            ModalVisible: false,
            CalculatorVisible: false,

            shareVisible: false,
            userInfo: {}
        };
    },
    activated () {
        // this.getAgreement("share");
        this.PageList();
        this.getCommissionConfig();
        this.getUserInfo();

    },
    created () {
        // this.getAgreement("share");
    },
    mounted () {
        this.getShareInfo();
        // this.getConfigList();
        this.PageList();
    },
    methods: {
        //基本信息
        getUserInfo () {
            getUserInfo().then(response => {
                if (response.code == 200) {
                    this.userInfo = { ...response.data };
                }
            });
        },
        showShare () {
            this.shareVisible = true;
            setTimeout(() => {
                this.creatQrCode();
            }, 500)
        },
        showModal () {
            this.ModalVisible = true;
        },
        hideModal () {
            this.ModalVisible = false;
        },
        showCalculatorModal () {
            this.CalculatorVisible = true;
        },
        hideCalculatorModal () {
            this.CalculatorVisible = false;
        },
        //获取协议
        getAgreement (code) {
            getAgreement({ code }).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    this.agreementMap.set(code, data);
                }
            }).catch(error => { });
        },
        //商品配置
        getConfigList () {
            configList().then(response => {
                if (response.code == 200) {
                    this.config = response.data;
                    console.log(this.config);
                }
            });
        },
        //获取商品列表
        PageList () {
            const { postData } = this;
            pageList(postData)
                .then(response => {
                    if (response.code === 200) {
                        const { data } = response;
                        this.data = data;
                    }
                })
                .catch(error => { });
        },
        //获取佣金配置
        getCommissionConfig () {
            getCommissionConfig().then(response => {
                this.commissionConfig = response.data;
                console.log("获取佣金配置", this.commissionConfig)
                const { firstReward, secondReward, thirdReward, fourthReward } = this.commissionConfig;
                this.maxReward = (100 * (firstReward + secondReward + thirdReward + fourthReward)).toFixed(0);
            });
        },
        //获取分享基本信息
        getShareInfo () {
            shareInfo().then(response => {
                if (response.code == 200) {
                    this.registerUrl = response.data.registerUrl;
                    this.shareTitle = response.data.title;
                    this.shareRemark = response.data.shareRemark;
                    this.shareRegisterUrl = "http://connect.qq.com/widget/shareqq/index.html?url=" + encodeURIComponent(this.registerUrl) + "&title=" + this.shareTitle + "&summary=" +
                        this.shareRemark + "&pics=http%3A%2F%2Fbbs.sibanyun.com%2Flogo.png&site=QQ%E5%88%86%E4%BA%AB&style=102&width=163&height=124&showcount=";
                    this.method = response.data.extensionMethod;
                    this.rule = response.data.commissionRules;
                    // this.creatQrCode();
                }
            });
        },
        //获取分享个人列表
        getShareUserList () {
            shareUserList(this.postData).then(response => {
                if (response.code == 200) {
                    const childrenNav = [];
                    const { data } = response;
                    const { records, total, current, size } = data;
                    userPageListToTree(records, childrenNav, 0);
                    this.haveExpandSet.clear();
                    this.dataKeySet.clear();
                    this.dataKeySet = new Set(records.map(f => f.id));
                    this.data = childrenNav;
                    Object.assign(this.pagination, {
                        total
                    });
                }
            });
        },
        //获取分享客户列表
        getShareCrmList () {
            shareCrmList(this.postData).then(response => {
                if (response.code == 200) {
                    const { data } = response;
                    const { records, total, current, size } = data;
                    this.crmData = records;
                    Object.assign(this.pagination, {
                        total
                    });
                }
            });
        },
        //生成二维码
        creatQrCode () {
            let qrcode = new QRCode(this.$refs.qrCodeUrl, {
                text: this.registerUrl, // 需要转换为二维码的内容
                width: 100,
                height: 100,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });
        },
        // 点击下载app二维码
        downloadQrCode (name) {
            var canvasData = document
                .getElementById("qrcode")
                .getElementsByTagName("canvas");
            var a = document.createElement("a");
            var event = new MouseEvent("click"); // 创建一个单击事件
            a.href = canvasData[0].toDataURL("image/png");
            a.download = "四班云推广二维码.png";
            a.click(); // 触发a的单击事件
        },
        //查询table 子集数据
        onTableExpand (expanded, record) {
            console.log(expanded, record);
            if (!expanded || this.haveExpandSet.has(record.id)) return false;
            const postData = {
                current: 1,
                size: -1,
                shareUserId: record.id
            };
            shareUserList(postData)
                .then(response => {
                    console.log(`获取：${record.dictLabel}——的子集`, response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records } = data;
                        records.forEach(item => {
                            if (!this.dataKeySet.has(item.id)) {
                                if (!item.treeLeaf) {
                                    item.children = [];
                                }
                                item.key = item.id;
                                record.children.push(item);
                                this.dataKeySet.add(item.id);
                            }
                        });
                        this.data = [...this.data];
                        this.haveExpandSet.add(record.id);
                    }
                })
                .catch(error => { });
        },
        // 复制
        onCopy () {
            this.$copyText(this.registerUrl)
                .then(res => {
                    this.$message.success("复制成功！");
                })
                .catch(err => {
                    this.$message.error("抱歉，复制失败！");
                });
        },
        //tab切换
        callback (key) {
            console.log(key);
            this.tabKey = key;
            if (key == 2) {
                this.getShareUserList();
            }
            if (key == 3) {
                this.getShareCrmList();
            }
        },
        //table 选中列
        selection (keys, info) {
            this.selectedKeys = keys;
            console.log(info);
            const ids = new Array();
            info.forEach(function (val) {
                ids.push(val.id);
            });
            this.selectIds = ids;
            this.selectedKeys = keys;
        },
        WxShareInfo () {
            getSignature(window.location.href).then(res => {
                localStorage.setItem("jsapi_ticket", res.data);
                console.log(res.data);
                //拿到后端给的这些数据
                let appId = res.data.appId;
                let timestamp = res.data.timestamp;
                let nonceStr = res.data.noncestr;
                let signature = res.data.signature;
                wx.config({
                    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: appId, // 必填，公众号的唯一标识，填自己的！
                    timestamp: timestamp, // 必填，生成签名的时间戳，刚才接口拿到的数据
                    nonceStr: nonceStr, // 必填，生成签名的随机串
                    signature: signature, // 必填，签名，见附录1
                    jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage"]
                });

                const _this = this;
                wx.ready(function () {
                    console.log("开始分享");
                    //分享到朋友圈
                    wx.onMenuShareTimeline({
                        title: _this.shareTitle, // 分享时的标题
                        desc: _this.shareRemark,
                        link: encodeURIComponent(_this.registerUrl), // 分享时的链接
                        imgUrl: "http://bbs.sibanyun.com/logo.png", // 分享时的图标
                        success: function () {
                            console.log("分享成功");
                        },
                        cancel: function () {
                            console.log("取消分享");
                        }
                    });
                    //分享给朋友
                    wx.onMenuShareAppMessage({
                        title: _this.shareTitle,
                        desc: _this.shareRemark,
                        link: encodeURIComponent(_this.registerUrl),
                        imgUrl: "http://bbs.sibanyun.com/logo.png",
                        type: "",
                        dataUrl: "",
                        success: function () {
                            console.log("分享成功");
                        },
                        cancel: function () {
                            console.log("取消分享");
                        }
                    });
                });
            });
        },
        //table分页分享
        onTableChange (pagination, filters, sorter) {
            console.log("pagination", pagination);
            Object.assign(this.postData, {
                current: pagination.current,
                size: pagination.pageSize
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            if (this.key == 2) {
                this.getShareUserList();
            } else {
                this.getShareCrmList();
            }
        },
        //改变折扣
        changeRate () {
            this.goodsInfo.discountRate = 0;
            if (this.config.length > 0 && this.goodsInfo.years > 0) {
                let config = this.config.find(f => f.years == this.goodsInfo.years);
                if (config != null) {
                    this.goodsInfo.discountRate = config.discountRate;
                } else {
                    this.goodsInfo.discountRate = this.config[this.config.length - 1].discountRate;
                }
            }
        },
        //商品列表改变年限
        useYearChang (e, item) {
            item.years = e.target.value;
            item.discountRate = this.config.find(f => f.years == item.years).discountRate;
            item.salePrice = parseFloat(item.years) * parseFloat(item.price) * parseFloat(item.discountRate) * 0.01
        },
        changePageSize (e) {
            const value = e.target.value;
            console.log(this.tabKey);
            if (this.tabKey == 2) {
                const { pagination } = this;
                Object.assign(this.postData, {
                    current: pagination.current,
                    size: pagination.pageSize
                });
                console.log(e, value);
                Object.assign(this.pagination, {
                    pageSize: Number.parseInt(value)
                });
                this.getShareUserList();
            } else {
                const { paginationCrm } = this;
                Object.assign(this.postData, {
                    current: paginationCrm.current,
                    size: paginationCrm.pageSize
                });
                console.log(e, value);
                Object.assign(this.paginationCrm, {
                    pageSize: Number.parseInt(value)
                });
                this.getShareCrmList();
            }
        }
    }
};
</script>
<style lang="less">
    .parent-content-wrapper {
        .content-wrapper {
            // min-height: 500px !important;
            height: 300px !important;
            flex-grow: 1 !important;
            margin: 0px !important;
        }
        .ant-form-item-label {
            text-align: left !important;
        }
        .reward {
            .ant-form-item-control {
                line-height: 25px !important;
            }
            .reward-label {
                display: inline-block;
                // width: 130px;
                margin-left: 50px;
                font-weight: 700;
                color: rgba(0, 0, 0, 0.85);
            }
        }
        .avatar-uploader > .ant-upload {
            width: 110px;
            height: 110px;
        }
        .ant-upload-select-picture-card i {
            font-size: 32px;
            color: #999;
        }
        .ant-upload-select-picture-card .ant-upload-text {
            margin-top: 8px;
            color: #666;
        }
        .user-class .ant-form-item {
            font-size: 12px;
            margin-bottom: 2px !important;
        }
        .form-inline label {
            justify-content: left !important;
        }
        .form-inline > .col {
            margin-bottom: 1.5rem !important;
        }
        .icons-list /deep/ .anticon {
            margin-right: 8px;
            font-size: 16px;
        }
        .ant-advanced-search-form {
            padding: 24px;
            background: #fbfbfb;
        }

        .ant-advanced-search-form .ant-form-item {
            display: flex;
        }

        .ant-advanced-search-form .ant-form-item-control-wrapper {
            flex: 1;
        }

        #components-form-demo-advanced-search .ant-form {
            max-width: none;
        }
        #components-form-demo-advanced-search .search-result-list {
            margin-top: 16px;
            background-color: #fafafa;
            min-height: 200px;
            text-align: center;
            padding-top: 80px;
        }
        // .crm-btn {
        //   margin-left: 10px;
        //   margin-bottom: 10px;
        // }
        .gutter-box {
            border: 3px #c0c0c0 solid;
            padding: 5px 0;
            max-width: 250px;
            height: 350px;
            text-align: center;
        }
        .googs-ul {
            text-align: left;
            margin-left: 20px;
            margin-top: 20px;
        }
        .buy-div {
            width: 100px;
            height: 30px;
            background: #00a0e9;
            margin: auto;
            text-align: center;
            line-height: 30px;
            border-radius: 20px;
            color: #f2f2f2;
            cursor: pointer;
        }
    }

    .user-class {
        min-height: 209px;
    }
</style>

<style lang="less" scoped>
    .money-set-wrapper {
        border-radius: 4px;
        height: 80px;
        box-sizing: border-box;
        .goods-img {
            width: 60px;
            height: 60px;
            padding-top: 6px;
            float: left;
            img {
                width: 60px;
                height: 60px;
                border-radius: 4px;
            }
        }
        .goods-explain {
            float: left;
            width: 45%;
            margin-left: 10px;
        }
    }
</style>